<?php

namespace addons\qingdong\model;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 *合同表
 */
class Contract Extends Model {

	use SoftDelete;
    // 表名,不含前缀
    protected $name = 'qingdong_contract';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';


	//创建合同
	public static function createContract($params) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name, 'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}else{
                if($params[$name] === ''){
                    $params[$name]=NULL;
                }
            }
		}
        $product = [];
        if (isset($params['product']) && $params['product']) {
            $product = $params['product'];
            unset($params['product']);
            foreach ($product as $tkey => $t) {
                $parts=$t['parts']??[];
                $new=[];
                if($parts){
                    foreach ($parts as $v){
                        if(!isset($v['part_id'])){
                            continue;
                        }
                        $new[]=['part_id'=>$v['part_id'],'number'=>$v['number']];
                    }
                }
                $product[$tkey]['parts'] = json_encode($new);
            }
        }
        if (isset($params['ratio_id']) && $params['ratio_id'] == 0) {
            $params['ratios'] = '';
        }
        if (isset($params['ratios']) && $params['ratios']) {
            foreach ($params['ratios'] as $v) {
                if (empty($v['staff_id'])) {
                    throw new Exception('业绩归属人必须全部选择');
                }
            }
            $params['ratios'] = json_encode($params['ratios']);
        }
        $customer=Customer::where(['id'=>$params['customer_id']])->find();
        if(empty($customer)){
            throw new Exception('客户不存在');
        }
        $params['owner_staff_id'] = $customer->owner_staff_id;

        $staff = Staff::info();
        if (!empty($staff)) {
            $params['create_staff_id'] = $staff->id;
        }

        $flow = Flow::getsteplist(Flow::CONTRACT_STATUS);
        $params['flow_id'] = $flow['flow_id'];
        $params['order_id'] = $flow['order_id'];

        if ($flow['status'] == 0) {//发起人自选
            if (empty($params['flow_staff_ids'])) {
                throw new Exception('审批人必须选择');
            }
            $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
        } else {
            $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
        }
		$Model = new self;
        $result = $Model->allowField(true)->save($params);

		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($Model->getError());
		}

		$lastId     = $Model->id;
		$otherModel = new ContractOther();
		if ($otherModel->save(['id' => $lastId, 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)]) === false) {
			// 验证失败 输出错误信息
			throw new Exception($otherModel->getError());
		}
        $addRatios = [];

        if (isset($params['ratios']) && $params['ratios']) {
            $ratios=json_decode($params['ratios'],true);
            foreach ($ratios as $v) {
                $addRatios[] = [
                    'contract_id' => $lastId,
                    'ratio' => $v['ratio'],
                    'staff_id' => $v['staff_id'],
                    'ratio_money' => $params['money'] * ($v['ratio'] / 100)
                ];
            }
        }


        //业绩分成 默认自己全部
        if (empty($addRatios)) {
            $addRatios[] = [
                'contract_id' => $lastId,
                'ratio' => 100,
                'staff_id' => isset($params['owner_staff_id']) ? $params['owner_staff_id'] : $staff->id ,
                'ratio_money' => $params['money']
            ];
        }
        if ($addRatios) {
            $ratioModel = new ContractRatio();
            $ratioModel->insertAll($addRatios);
        }
        $addProduct = [];
        foreach ($product as $v) {
            if (isset($v['id'])){
                unset($v['id']);
            }
            $v['contract_id'] = $lastId;
            $addProduct[]     = $v;
        }
        if ($addProduct) {
            $productModel = new ContractProduct();
            $productModel->allowField(true)->saveAll($addProduct);
        }
        if ($flow['status'] == 1) {//固定审批
            //发送审批通知
            Flow::sendStepRecord($flow,Flow::CONTRACT_STATUS, $lastId);
        } else {//发起人自选 依次审批
            $staff_id   = explode(',', $params['flow_staff_ids'])[0];
            if ($staff_id) {
                ExamineRecord::addExaminse(ExamineRecord::CONTRACT_TYPE, $lastId, $staff_id);
            }
        }

		OperationLog::createLog(OperationLog::CONTRACT_TYPE, $lastId, '创建合同');

		return true;
	}


	//修改合同
	public static function updateContract($params) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name, 'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}else{
                if($params[$name] === ''){
                    $params[$name]=NULL;
                }
            }
		}
        $product = [];
        if (isset($params['product'])) {
            $product = $params['product'];
            unset($params['product']);
            foreach ($product as $tkey => $t) {
                $parts=$t['parts']??[];
                $new=[];
                if($parts){
                    foreach ($parts as $v){
                        if(!isset($v['part_id'])){
                            continue;
                        }
                        $new[]=['part_id'=>$v['part_id'],'number'=>$v['number']];
                    }
                }
                $product[$tkey]['parts'] = json_encode($new);
            }
        }


        if (isset($params['ratio_id']) && $params['ratio_id'] == 0) {
            $params['ratios'] = '';
        }
        if (isset($params['ratios']) && $params['ratios']) {
            foreach ($params['ratios'] as $v) {
                if (empty($v['staff_id'])) {
                    throw new Exception('业绩归属人必须全部选择');
                }
            }
            $params['ratios'] = json_encode($params['ratios']);
        }
        $flow = Flow::getsteplist(Flow::CONTRACT_STATUS);
        $params['flow_id'] = $flow['flow_id'];
        $params['order_id'] = $flow['order_id'];

        if ($flow['status'] == 0) {//发起人自选
            if (empty($params['flow_staff_ids'])) {
                throw new Exception('审批人必须选择');
            }
            $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
        } else {
            $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
        }

		$Model                  = new self;
		$params['check_status'] = 1;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $Model->allowField(true)->save($params, ['id' => $params['id']]);
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($Model->getError());
		}

		$otherModel = new ContractOther();
		if ($otherModel->save(['otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)], ['id' => $params['id']]) === false) {
			// 验证失败 输出错误信息
			throw new Exception($otherModel->getError());
		}
        $addRatios = [];
        if (isset($params['ratios']) && $params['ratios']) {
            $ratios=json_decode($params['ratios'],true);
            foreach ($ratios as $v) {
                $addRatios[] = [
                    'contract_id' => $params['id'],
                    'ratio' => $v['ratio'],
                    'staff_id' => $v['staff_id'],
                    'ratio_money' => $params['money'] * ($v['ratio'] / 100)
                ];
            }
        }
        //业绩分成 默认自己全部
        $staff = Staff::info();
        if (empty($addRatios)) {
            $addRatios[] = [
                'contract_id' => $params['id'],
                'ratio' => 100,
                'staff_id' => isset($params['owner_staff_id']) ? $params['owner_staff_id'] : $staff->id,
                'ratio_money' => $params['money']
            ];
        }
        if ($addRatios) {
            $ratioModel = new ContractRatio();
            $ratioModel->where(['contract_id' => $params['id']])->delete();
            $ratioModel->insertAll($addRatios);
        }

        $addProduct = [];
		if($product){
            foreach ($product as $v) {
                if (isset($v['id'])){
                    unset($v['id']);
                }
                $v['contract_id'] = $params['id'];
                $addProduct[]     = $v;
            }
        }
        if ($addProduct) {
            $productModel = new ContractProduct();
            $productModel->where(['contract_id' => $params['id']])->delete();
            $productModel = new ContractProduct();
            $productModel->allowField(true)->saveAll($addProduct);
        }

        if ($flow['status'] == 1) {//固定审批
            //发送审批通知
            Flow::sendStepRecord($flow,Flow::CONTRACT_STATUS, $params['id']);
        } else {//发起人自选 依次审批
            $staff_id   = explode(',', $params['flow_staff_ids'])[0];
            if ($staff_id) {
                ExamineRecord::addExaminse(ExamineRecord::CONTRACT_TYPE, $params['id'], $staff_id);
            }
        }

		return true;
	}


	//获取更新时间
	public function getUpdatetimeAttr($value) {
		return date('Y-m-d H:i:s', $value);
	}


	//负责人
	public function ownerStaff() {
		return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name');
	}

    //获取合同相关信息
    public function contractOther() {
        return $this->belongsTo(ContractOther::class,'id','id');
    }


	//客户
	public function customer() {
		return $this->hasOne(Customer::class, 'id', 'customer_id')->field('id,name,follow');
	}
    //商机
    public function business() {
        return $this->hasOne(Business::class, 'id', 'business_id')->field('id,name');
    }

	//联系人
	public function contacts() {
		return $this->hasOne(Contacts::class, 'id', 'contacts_id')->field('id,name');
	}


	//员工
	public function staff() {
		return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name,img,department_id,post');
	}


	//签约人
	public function orderStaff() {
		return $this->hasOne(Staff::class, 'id', 'order_staff_id')->field('id,name');
	}

    //产品
    public function product(){
        return $this->hasMany(ContractProduct::class,'contract_id','id')->with('product');
    }

	//回款统计
	public function receivables() {
		return $this->hasOne(Receivables::class, 'contract_id', 'id')->where(['check_status' => 2])->group('contract_id')->field('contract_id,sum(money) as repayment_money');
	}


    //导入
    public static function importContract($data) {
        $addContacts = [];
        $addOther     = [];
        $addratio = [];
        foreach ($data as $params) {
            //自定义字段
            $other = [];
            foreach ($params as $name => $val) {
                if (strstr($name, 'other_') !== false) {
                    if(is_array($val)){
                        $other[$name] = implode(',',$val);
                    }else{
                        $other[$name] = $val;
                    }
                    unset($params[$name]);
                }else{
                    if($params[$name] === ''){
                        $params[$name]=NULL;
                    }
                }
            }
            $params['createtime'] = time();
            $params['updatetime'] = time();
            $params['check_status']   = 2;
            $other['id']           = $params['id'];
            $addOther[]            = ['id' => $params['id'], 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)];
            $addContacts[]        = $params;
            $addratio[] = array(
                'contract_id'=>$params['id'],
                'ratio'=>100,
                'staff_id'=>isset($params['owner_staff_id'])?$params['owner_staff_id']:0,
                'ratio_money'=>isset($params['money'])?$params['money']:0,

            );
        }

        $model = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $model->allowField(true)->insertAll($addContacts);

        $otherModel = new ContractOther();
        $otherModel->allowField(true)->insertAll($addOther);

        $modelRatio = new ContractRatio();
        $modelRatio->allowField(true)->insertAll($addratio);

        return true;
    }

    public static function getNum()
    {
        return 'C' . date('Ymd') . rand(10000,99999);
    }
}
